package com.pig4cloud.pig.module.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.emoji.EmojiUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.estate.RepairRecord;
import com.pig4cloud.pig.module.api.entity.estate.RepairRecordImg;
import com.pig4cloud.pig.module.api.entity.estate.Worker;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.estate.IRepairRecordImgService;
import com.pig4cloud.pig.module.service.estate.IRepairRecordService;
import com.pig4cloud.pig.module.service.estate.IWorkerService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.RequiredArgsConstructor;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 报修记录Controller
 *
 * @author ruoyi
 * @date 2021-08-24
 */
@Validated
@Api(value = "报修记录控制器", tags = {"报修记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/repair/record")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class RepairRecordController  {

    private final IRepairRecordService repairRecordService;
	private final IRepairRecordImgService repairRecordImgService;
	private final IWorkerService workerService;
    private final IEstateService estateService;
    private final IWxUserService wxUserService;
	private final IWxTemplateService wxTemplateService;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;

    /**
     * 查询报修记录列表
     */
    @ApiOperation("查询报修记录列表")
    @PreAuthorize("@pms.hasPermission('module:repairrecord:list')")
    @GetMapping("/list")
    public TableDataInfo<RepairRecord> list(@Validated RepairRecord repairRecord) {
		PigUser sysUser = SecurityUtils.getUser();
        QueryWrapper<RepairRecord> qw = new QueryWrapper<>();
        if(sysUser.getUserType() == 2){//物业公司
            qw.eq("property_id",sysUser.getPropertyId());
        } else if(sysUser.getUserType() == 3){//小区
            qw.eq("estate_id",sysUser.getEstateId());
        }
        if(StrUtil.isNotEmpty(repairRecord.getPhoneNum())){
			qw.eq("phone_num",repairRecord.getPhoneNum());
		}

		if(repairRecord.getState() !=null){
			qw.eq("state",repairRecord.getState());
		}
        qw.orderByDesc("create_time");
        TableDataInfo<RepairRecord> td = PageUtils.buildDataInfo(repairRecordService.page(PageUtils.buildPage(),qw));
        List<RepairRecord> list = td.getData();
        list.forEach(repairRecord1 -> {
			List<String> imgUrls = new ArrayList<>();
			QueryWrapper<RepairRecordImg> qwRecordImg = new QueryWrapper<>();
			qwRecordImg.eq("record_id",repairRecord.getId());
			qwRecordImg.eq("img_type", 0);
			List<RepairRecordImg> recordImgs = repairRecordImgService.list(qwRecordImg);
			if(CollUtil.isNotEmpty(recordImgs)){
				for (RepairRecordImg recordImg : recordImgs){
					imgUrls.add(imgUrl + recordImg.getImgUrl());
				}
				repairRecord1.setImgUrlList(imgUrls);
			}


			List<String> opImgUrls = new ArrayList<>();
			QueryWrapper<RepairRecordImg> qwRecordOpImg = new QueryWrapper<>();
			qwRecordOpImg.eq("record_id",repairRecord.getId());
			qwRecordOpImg.eq("img_type", 1);
			List<RepairRecordImg> recordOpImgs = repairRecordImgService.list(qwRecordOpImg);
			if(CollUtil.isNotEmpty(recordImgs)){
				for (RepairRecordImg recordImg : recordOpImgs){
					opImgUrls.add(imgUrl + recordImg.getImgUrl());
				}
				repairRecord1.setOpImgUrlList(opImgUrls);
			}

            WxUser wxUser = wxUserService.findById(repairRecord1.getUserId());
            if(wxUser != null){
                repairRecord1.setNickName(EmojiUtil.toUnicode(wxUser.getNickName()));
            }
        });
        return td;
    }

    /**
     * 导出报修记录列表
     */
    @ApiOperation("导出报修记录列表")
    @PreAuthorize("@pms.hasPermission('module:repairrecord:export')")
    @SysLog("报修记录")
    @GetMapping("/export")
    public List export(@Validated RepairRecord repairRecord) {
        List<RepairRecord> list = repairRecordService.list();
//        // ExcelUtil<RepairRecord> util = new // ExcelUtil<RepairRecord>(RepairRecord.class);
        return list;//util.exportExcel(list, "报修记录");
    }

    /**
     * 获取报修记录详细信息
     */
    @ApiOperation("获取报修记录详细信息")
    @PreAuthorize("@pms.hasPermission('module:repairrecord:query')")
    @GetMapping("/{id}")
    public R<RepairRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        RepairRecord repairRecord = repairRecordService.getById(id);
        if(repairRecord!=null){
			List<String> imgUrls = new ArrayList<>();
			QueryWrapper<RepairRecordImg> qwRecordImg = new QueryWrapper<>();
			qwRecordImg.eq("record_id",repairRecord.getId());
			qwRecordImg.eq("img_type", 0);
			List<RepairRecordImg> recordImgs = repairRecordImgService.list(qwRecordImg);
			if(CollUtil.isNotEmpty(recordImgs)){
				for (RepairRecordImg recordImg : recordImgs){
					imgUrls.add(imgUrl + recordImg.getImgUrl());
				}
				repairRecord.setImgUrlList(imgUrls);
			}


			List<String> opImgUrls = new ArrayList<>();
			QueryWrapper<RepairRecordImg> qwRecordOpImg = new QueryWrapper<>();
			qwRecordOpImg.eq("record_id",repairRecord.getId());
			qwRecordOpImg.eq("img_type", 1);
			List<RepairRecordImg> recordOpImgs = repairRecordImgService.list(qwRecordOpImg);
			if(CollUtil.isNotEmpty(recordImgs)){
				for (RepairRecordImg recordImg : recordOpImgs){
					opImgUrls.add(imgUrl + recordImg.getImgUrl());
				}
				repairRecord.setOpImgUrlList(opImgUrls);
			}

			WxUser wxUser = wxUserService.findById(repairRecord.getUserId());
			if(wxUser != null){
				repairRecord.setNickName(EmojiUtil.toUnicode(wxUser.getNickName()));
			}
		}
        return R.ok(repairRecord);
    }

    /**
     * 新增报修记录
     */
    @ApiOperation("新增报修记录")
    @PreAuthorize("@pms.hasPermission('module:repairrecord:add')")
    @SysLog("报修记录")
    @PostMapping()
    public R<Void> add(@Valid @RequestBody RepairRecord repairRecord) {
		if(repairRecord.getOpWorkerId()!=null) {
			Worker worker = workerService.getById(repairRecord.getOpWorkerId());
			if (worker != null) {
				repairRecord.setOpUserName(worker.getWorkerName());
				repairRecord.setOpWorkerPhone(worker.getWorkerPhone());
			}
		}
        return R.okByRow(repairRecordService.save(repairRecord) ? 1 : 0);
    }

    /**
     * 修改报修记录
     */
    @ApiOperation("修改报修记录")
    @PreAuthorize("@pms.hasPermission('module:repairrecord:edit')")
    @SysLog("报修记录")
    @PutMapping()
    public R<Void> edit(@Valid @RequestBody RepairRecord repairRecord) {
    	if(repairRecord.getOpWorkerId()!=null){
			Worker worker = workerService.getById(repairRecord.getOpWorkerId());
			if(worker!=null){
				repairRecord.setState(1);
				repairRecord.setOpState(1);
				repairRecord.setOpUserName(worker.getWorkerName());
				repairRecord.setOpWorkerPhone(worker.getWorkerPhone());
				repairRecord.setOpWxUserId(worker.getWxUserId());
				repairRecord.setOpWxNickName(worker.getNickName());
			}
		}
    	boolean bl = repairRecordService.updateById(repairRecord);
    	if(bl){
			wxTemplateService.sendWxMsgRepair(repairRecord,1);
		}
        return R.okByRow(bl ? 1 : 0);
    }

    /**
     * 删除报修记录
     */
    @ApiOperation("删除报修记录")
    @PreAuthorize("@pms.hasPermission('module:repairrecord:remove')")
    @SysLog("报修记录")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(repairRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
